package com.ruoyi.slope.api.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;

import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.slope.api.domain.SlopeInfoDto;
import com.ruoyi.slope.api.service.SlopeApiService;
import com.ruoyi.slope.api.service.SlopeDataApiService;
import com.ruoyi.slope.api.service.SlopeInfoApiService;
import com.ruoyi.slope.info.domain.SlopeInfo;
import com.ruoyi.slope.warning.info.domain.SlopeWarningInfo;
import com.ruoyi.slope.warning.info.service.impl.SlopeWarningInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 落石监测图片Controller
 *
 * @author ruoyi
 * @date 2025-07-27
 */
@RestController
@RequestMapping("/api")
public class SlopeApiController extends BaseController {

    @Autowired
    private SlopeApiService slopeApiService; // 新建的业务层

    @Autowired
    private SysLoginService loginService;

    @Resource
    private SlopeInfoApiService slopeInfoApiService;

    @Resource
    private SlopeDataApiService slopeDataApiService;

    /**
     * 接收 AI 图片
     */
    @PostMapping("/upload-ai-image")
    public AjaxResult uploadImage(@RequestBody Map<String, Object> payload) {
        return slopeApiService.handleUploadAiImage(payload);
    }

    /**
     * 接收设备数据（测点 JSON / 图片分片）
     */
    @PostMapping("/devices/datapoints")
    public AjaxResult receiveData(HttpServletRequest request,
                                  @RequestParam(value = "type", required = false) Integer type) {
        return slopeApiService.handleDeviceData(request, type);
    }

    /**
     * 上游调用获取 token
     */
    @PostMapping("/getToken")
    public AjaxResult getToken(@RequestBody LoginBody loginBody,
                               HttpServletRequest request) {
        // 1. 从 JSON 获取用户名和密码
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();

        // 2. 从请求头获取自定义参数
        String other = request.getHeader("other");

        // 这里可以加一层逻辑，比如必须要带 other=1 才能生成 token
        if (!"1".equals(other)) {
            return AjaxResult.error("非法请求，缺少有效请求头");
        }

        // 3. 调用 RuoYi 内置登录逻辑
        String token = loginService.login(username, password, null, null, 1);

        // 4. 返回 token
        return AjaxResult.success("token", token);
    }

    @GetMapping("/getSlopeInfo")
    public AjaxResult getSlopeInfo() {
        List<SlopeInfoDto> slopeList = slopeInfoApiService.getSlopeInfo();

        Map<String, Object> result = new HashMap<>();
        result.put("slopeInfo", slopeList);

        // 符合你给的格式
        return AjaxResult.success(result);
    }

    /**
     * 获取边坡项目监测最新数据信息（接收 JSON 参数）
     * @param requestBody JSON 包含 slopecode
     * @return JSON 数据
     */
    @PostMapping("/getSlopeData")
    public Map<String, Object> getSlopeData(@RequestBody Map<String, String> requestBody) {
        Map<String, Object> result = new HashMap<>();
        try {
            String slopecode = requestBody.get("slopeCode");
            if (slopecode == null || slopecode.isEmpty()) {
                result.put("code", 400);
                result.put("msg", "slopecode不能为空");
                return result;
            }

            // 获取边坡最新监测数据
            Map<String, Object> data = slopeDataApiService.getAllSlopeData(slopecode);

            result.put("code", 0);
            result.put("msg", "success");
            result.put("data", data);
            return result;

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取边坡监测数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取边坡项目监测最新数据信息（接收 JSON 参数）
     * @param requestBody JSON 包含 slopecode
     * @return JSON 数据
     */
    @PostMapping("/getSlopeDataSet")
    public Map<String, Object> getSlopeDataSet(@RequestBody Map<String, String> requestBody) {
        Map<String, Object> result = new HashMap<>();
        try {
            String slopecode = requestBody.get("slopeCode");
            if (slopecode == null || slopecode.isEmpty()) {
                result.put("code", 400);
                result.put("msg", "slopecode不能为空");
                return result;
            }

            // 获取边坡最新监测数据
            Map<String, Object> data = slopeDataApiService.getAllSlopeDataSet(slopecode);

            result.put("code", 0);
            result.put("msg", "success");
            result.put("data", data);
            return result;

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取边坡监测数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取边坡项目监测最新报警信息
     * 请求方式：GET
     * 请求地址：http://39.107.238.187:8080/api/getAlarmData
     * 请求头：Authorization: bearer {access_token}
     * 参数：slopecode (必填)
     */
    @GetMapping("/getAlarmData")
    public Map<String, Object> getAlarmData(@RequestBody Map<String, String> requestBody) {
        Map<String, Object> result = new HashMap<>();
        try {
            String slopecode = requestBody.get("slopeCode");
            if (slopecode == null || slopecode.isEmpty()) {
                result.put("code", 400);
                result.put("msg", "slopecode不能为空");
                return result;
            }

            // 获取边坡最新监测数据
            Map<String, Object> data = slopeDataApiService.getAllSlopeWarningInfo(slopecode);

            result.put("code", 0);
            result.put("msg", "success");
            result.put("data", data);
            return result;

        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取边坡监测数据失败: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取指定设备某段时间的监测数据
     * 请求方式：GET
     * 请求地址：http://39.107.238.187:8080/api/getMonitorData
     * 请求头：Authorization: bearer {access_token}
     * 参数：monitorType (必填)、deviceSn (必填)、startTime (必填)、endTime (必填)
     * 时间格式：yyyy-MM-dd HH:mm:ss
     */
    @GetMapping("/getMonitorData")
    public Map<String, Object> getMonitorData(@RequestBody Map<String, String> requestBody) {
        Map<String, Object> result = new LinkedHashMap<>();
        try {
            String monitorType = requestBody.get("monitorType");
            String deviceSn = requestBody.get("deviceSn");
            String startTimeStr = requestBody.get("startTime");
            String endTimeStr = requestBody.get("endTime");

            // 参数校验
            if (monitorType == null || monitorType.isEmpty()
                    || deviceSn == null || deviceSn.isEmpty()
                    || startTimeStr == null || startTimeStr.isEmpty()
                    || endTimeStr == null || endTimeStr.isEmpty()) {
                result.put("code", 400);
                result.put("msg", "monitorType、deviceSn、startTime、endTime不能为空");
                return result;
            }

            // 解析时间，使用 Date + SimpleDateFormat
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime = sdf.parse(startTimeStr);
            Date endTime = sdf.parse(endTimeStr);

            // 校验时间区间是否在1个月内（按毫秒计算差值）
            long diffMillis = endTime.getTime() - startTime.getTime();
            if (diffMillis < 0) {
                result.put("code", 400);
                result.put("msg", "结束时间不能早于开始时间");
                return result;
            }
            long days = diffMillis / (1000 * 60 * 60 * 24);
            if (days > 31) {
                result.put("code", 400);
                result.put("msg", "时间区间不能超过1个月");
                return result;
            }

            // 调用业务逻辑，查询监测数据
            Map<String, Object> data = slopeDataApiService.getMonitorData(monitorType, deviceSn, startTime, endTime);

            result.put("code", 0);
            result.put("msg", "success");
            result.put("deviceSn", deviceSn);
            result.put("monitorType", monitorType);
            result.put("data", data);
            return result;

        } catch (ParseException e) {
            result.put("code", 400);
            result.put("msg", "时间格式不正确，必须为yyyy-MM-dd HH:mm:ss");
            return result;
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "获取监测数据失败: " + e.getMessage());
            return result;
        }
    }


}


